import React, { useEffect, useRef, useState } from 'react'
import _ from 'lodash';
import {
    UserOutlined,
    HomeOutlined,
    UserSwitchOutlined,
    GoldOutlined,
    IdcardOutlined,
    TeamOutlined,
    ApartmentOutlined,
    ContactsOutlined,
    FormOutlined,
    SnippetsOutlined,
    FileExcelOutlined,
    FileDoneOutlined,
    FileUnknownOutlined,
    ReconciliationOutlined,
    UnorderedListOutlined,
    AuditOutlined,
    CalendarOutlined,
    UserAddOutlined
} from '@ant-design/icons';
import { Layout, Menu } from 'antd';
import style from './index.less';
import { connect, useLocation, useNavigate } from 'umi';
import type { MenuProps } from 'antd'

// 定义MenuItem类型
type MenuItem = Required<MenuProps>['items'][number];
// 定义一个接口，规范menuItem的属性有哪些
interface IMenuItem {
    label: React.ReactNode,
    key: React.Key,
    icon?: React.ReactNode,
    children?: MenuItem[],
    type?: 'group',
    pagepermisson?: number
}

const { Sider } = Layout;
function StandBoxSider(props: any) {
    const { collapsed, dispatch, routeList,currentUserList } = props;

    //获取路由的location属性
    const location = useLocation()

    // 获取当前路由路径的父路径，用于menu菜单，选中的菜单项 key 数组
    const openKeys = useRef([`/${location.pathname.split('/')[1]}`]);

    // 路由跳转方法
    const navigate = useNavigate();

    // 记录当前用户的权限路由信息
    const [currentUserLimits,setCurrentUserLimits]=useState(null)
    // 获取登录时，在localStorage写下的用户信息，连续解构出用户名和角色名
    // const {role:{rights}}=JSON.parse((localStorage.getItem('token') as string))[0];
    useEffect(()=>{
        if(currentUserList.length<=0){
            if(localStorage.getItem('token')){
                setCurrentUserLimits(JSON.parse((localStorage.getItem('token')as string))[0])
            }
            else{
                navigate('/login')
            }
        }
        else{
            setCurrentUserLimits(currentUserList[0])
        }
    },[currentUserList])


    // 菜单数据
    const [items, setItems] = useState<any>(routeList);

    //定义一个图标列表，后续根据路径选取图标
    const iconLists = {
        '/home': <HomeOutlined />,
        '/right-manage': <GoldOutlined />,
        '/right-manage/role/list': <TeamOutlined />,
        '/right-manage/right/list': <ContactsOutlined />,
        '/user-manage': <UserOutlined />,
        '/user-manage/list': <UserSwitchOutlined />,
        '/news-manage': <FormOutlined />,
        '/news-manage/add': <UserAddOutlined />,
        '/news-manage/draft': <SnippetsOutlined />,
        '/news-manage/category': <CalendarOutlined />,
        '/audit-manage': <HomeOutlined />,
        '/audit-manage/audit': <AuditOutlined />,
        '/audit-manage/list': <UnorderedListOutlined />,
        '/publish-manage': <ReconciliationOutlined />,
        '/publish-manage/unpublished': <FileUnknownOutlined />,
        '/publish-manage/published': <FileDoneOutlined />,
        '/publish-manage/sunset': <FileExcelOutlined />,
    }
    // console.log(iconLists['/audit-manage'])
    // 创建一个递归（自己调用自己）函数，返回一个MenuItem对象
    function getItem(
        menuItem: IMenuItem
    ): MenuItem {
        if (menuItem.pagepermisson === 1) {
            if ((menuItem.children as Array<any>)?.length > 0) {
                menuItem.children = _.cloneDeep(menuItem.children)?.filter((item: any) => item.pagepermisson === 1).map((childItem: any) => {
                    // Reflect.deleteProperty(childItem,'rightId')
                    return getItem(childItem)
                })
            }
            return (menuItem.children as Array<any>)?.length > 0 ? {
                key: menuItem.key,
                icon: (iconLists as any)[menuItem.key],
                children: menuItem.children,
                label: menuItem.label,
                type: menuItem.type,
            } as MenuItem : {
                key: menuItem.key,
                icon: (iconLists as any)[menuItem.key],
                label: menuItem.label,
                type: menuItem.type,
            } as MenuItem;
        }
        else {
            return null;
        }
    }

    // 发起网络请求，动态获取菜单数据，然后更新状态，再有Menu菜单组件通过数据生成菜单列表
    useEffect(() => {
        if (routeList.length === 0) {
            dispatch({
                type: 'StandBox/getRouteList',
                payload: {}
            })
        }
        else {
            // 筛选出单独页面功能的路由信息（pagepermisson === 1）
            let menus:Array<any> = _.cloneDeep(routeList)?.filter((item: any) => {
                return item.pagepermisson === 1
            })
            if((currentUserLimits as any)?.role){
                menus=filterRoute(menus);
            }
            
            // console.log('menus',menus);
            menus=menus.map((item:any)=>{
                return getItem(item)
            })
            // console.log('menus',menus);
            // 设置menu菜单数据
            setItems(menus);
        }
    }, [routeList,currentUserLimits])
    
    //筛选出与个人信息符合的路由,递归
    const filterRoute=(items:Array<any>)=>{
        return items.filter(item=>{
            const{role:{rights:{checked}}}=currentUserLimits as any;
            const{role:{rights}}=currentUserLimits as any;
            if((item.children as Array<any>)?.length>0){
                item.children=filterRoute(item.children);
            }
            if(checked){
                return checked?.includes(item.key)
            }
            else{
                return rights?.includes(item.key)
            }
        })
    }

    //#region 静态声明菜单结构数组，用于后续 显示主菜单以及子菜单 （已废用）
    const MenuItemArray = [
        {
            // 标题名
            label: '首页',
            // 用路径作key值，方便后续进行路由跳转
            key: '/home',
            // 图标 
            icon: <HomeOutlined />,
        },
        {
            // 标题名
            label: '用户管理',
            // 用路径作key值，方便后续进行路由跳转
            key: '/user-manage',
            // 图标 
            icon: <UserOutlined />,
            children: [
                {
                    label: '用户列表',
                    // 用路径作key值，方便后续进行路由跳转
                    key: '/user-manage/list',
                    // 图标 
                    icon: <UserSwitchOutlined />,
                }
            ],
        },
        {
            // 标题名
            label: '权限管理',
            // 用路径作key值，方便后续进行路由跳转
            key: '/right-manage',
            // 图标 
            icon: <GoldOutlined />,
            children: [
                {
                    label: '角色管理',
                    // 用路径作key值，方便后续进行路由跳转
                    key: '/right-manage/role',
                    // 图标 
                    icon: <IdcardOutlined />,
                    children: [
                        {
                            label: '角色列表',
                            // 用路径作key值，方便后续进行路由跳转
                            key: '/right-manage/role/list',
                            // 图标 
                            icon: <TeamOutlined />,
                        }
                    ]
                },
                {
                    label: '权限分配',
                    // 用路径作key值，方便后续进行路由跳转
                    key: '/right-manage/right',
                    // 图标 
                    icon: <ApartmentOutlined />,
                    children: [
                        {
                            label: '权限列表',
                            // 用路径作key值，方便后续进行路由跳转
                            key: '/right-manage/right/list',
                            // 图标 
                            icon: <ContactsOutlined />,
                        }
                    ]
                }
            ],
        },
        {
            // 标题名
            label: '新闻管理',
            // 用路径作key值，方便后续进行路由跳转
            key: '/new-manage',
            // 图标 
            icon: <FormOutlined />,
            children: [
                {
                    label: '草稿箱',
                    // 用路径作key值，方便后续进行路由跳转
                    key: '/new-manage/draft',
                    // 图标 
                    icon: <SnippetsOutlined />,
                }
            ],
        },
    ];
    //#endregion

    // 点击某个菜单项，跳转页面
    const handelSkipPage = (e: any) => {
        // e.key是MenuItem的路径
        navigate(e.key);
    }

    //获取当前路由路径，并放置数组中
    const selectedKeys = [location.pathname];

    return (
        <Sider
            breakpoint="lg"
            onBreakpoint={(broken) => {
                console.log(broken);
            }}
            onCollapse={(collapsed, type) => {
                console.log(collapsed, type);
            }}
            trigger={null}
            collapsible
            collapsed={collapsed}
            style={{
                overflow: 'auto',
                height: '100vh',
                position: 'fixed',
                left: 0,
                top: 0,
                bottom: 0,
            }}
        >
            <div className={style.logo}><span>全球新闻发布系统</span></div>
            <Menu
                theme="dark"
                mode="inline"
                selectedKeys={selectedKeys}
                defaultOpenKeys={openKeys.current}
                items={items}
                onClick={(e) => { handelSkipPage(e) }}
            />
        </Sider>
    )
}

//映射redux公共状态到props属性中 
const mapStateToProps = (state: any) => {
    return {
        collapsed: state.StandBox.collapsed,
        routeList: state.StandBox.routeList,
        currentUserList:state.StandBox.currentUserList,
    }
}
// 使用 connect()()绑定组件
export default connect(mapStateToProps)(StandBoxSider)
